package com.example.todoapp.http.controllers;

import com.example.todoapp.data.entities.Tag;
import com.example.todoapp.data.entities.TagRepository;
import com.example.todoapp.http.responsestruct.ResponseResult;
import com.example.todoapp.http.todoltemrequest.TagRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class TagController {
    @Autowired
    private TagRepository tagRepository;

    // 获取标签列表
    @GetMapping("/tags")
    public ResponseResult<List<Tag>> getTags() {
        return ResponseResult.success(tagRepository.findAll());
    }

    // 获取单个标签
    @GetMapping("/tag/{id}")
    public ResponseResult<Tag> getTag(@PathVariable Long id) {
        return tagRepository.findById(id)
                .map(ResponseResult::success)
                .orElseGet(() -> new ResponseResult<>(404, "Tag not found", null));
    }

    // 新增标签
    @PostMapping("/tag")
    public ResponseResult<Tag> createTag(@RequestBody TagRequest request) {
        Tag tag = new Tag();
        tag.setName(request.getName());
        tag.setDescription(request.getDescriptions()); // 映射字段
        return ResponseResult.success(tagRepository.save(tag));
    }

    // 更新标签
    @PostMapping("/tag/{id}")
    public ResponseResult<Tag> updateTag(@PathVariable Long id, @RequestBody TagRequest request) {
        return tagRepository.findById(id)
                .map(tag -> {
                    tag.setName(request.getName());
                    tag.setDescription(request.getDescriptions());
                    return ResponseResult.success(tagRepository.save(tag));
                })
                .orElseGet(() -> new ResponseResult<>(404, "Tag not found", null));
    }
}